package com.shaoshaohuo.app.ui.ec;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.constant.ExtraName;
import com.shaoshaohuo.app.entity.BaseEntity;
import com.shaoshaohuo.app.entity.City;
import com.shaoshaohuo.app.entity.EcCategorySecond;
import com.shaoshaohuo.app.entity.EcCategoryThird;
import com.shaoshaohuo.app.entity.EcVarietyEntity;
import com.shaoshaohuo.app.entity.Market;
import com.shaoshaohuo.app.entity.PoiEntity;
import com.shaoshaohuo.app.entity.Province;
import com.shaoshaohuo.app.entity.post.BusinessPublish;
import com.shaoshaohuo.app.net.HttpRequest.RequestListener;
import com.shaoshaohuo.app.net.RequestService;
import com.shaoshaohuo.app.ui.BaseActivity;
import com.shaoshaohuo.app.ui.SelectProvinceActivity;
import com.shaoshaohuo.app.adapter.MarketSelectedAdapter;
import com.shaoshaohuo.app.adapter.VarietyGridviewAdapter;
import com.shaoshaohuo.app.view.MeasureGridView;
import com.shaoshaohuo.app.view.TopbarView;
import com.shaoshaohuo.app.utils.DeviceHelper;
import com.shaoshaohuo.app.utils.PoiEntityUtils;
import com.shaoshaohuo.app.utils.StringHelper;
import com.shaoshaohuo.app.view.citymenu.CascadingMenuPopWindow;
import com.shaoshaohuo.app.view.citymenu.interfaces.CascadingMenuViewOnSelectListener;
import com.shaoshaohuo.app.view.citymenu.entity.Area;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName ReleaseOpportunityActivity
 * @author linmu
 * @Decription 发布商机
 * @2015-8-30 上午11:43:44
 */
public class ReleaseOpportunityActivity extends BaseActivity implements OnClickListener {

    private static final int SELECT_MARKET_CITY = 1; 
    private static final int SELECT_MARKET = SELECT_MARKET_CITY+1; 
    private static final int SELECT_PRODUCT_TYPE = SELECT_MARKET+1; 
    private static final int SELECT_ADDRESS_POI = SELECT_PRODUCT_TYPE+1; 
    
	private TopbarView mTopbarView;

	private MeasureGridView mPinzhongGv;
	
//	private View mMarketLayout;
//	private MeasureListView mListView;
	private EditText mMarketNameText;
	private View mProductNameLayout;
	private TextView mProductNameEdit;
	private EditText mUnitNameEdit;
	private View mRecivAddressLayout;
    private TextView mRecivAddressText;
    private EditText mDetailAddressText;
	private EditText mContactPhoneEdit;
	private EditText mContactNameEdit;
	private Button mNextButton;
	private CascadingMenuPopWindow cascadingMenuPopWindow;
	private Province marketProvince;
    private City marketCity;
//    private Market selectMarket;
    private ArrayList<Market> mMarketList = new ArrayList<>();
	private MarketSelectedAdapter<Market> mMarketAdapter;
	
	private EcCategorySecond ecCategorySecond;
	private ArrayList<EcCategoryThird> mSelectVarietyList = new ArrayList<>();
	private VarietyGridviewAdapter<EcCategoryThird> mVarietyAdapter;
    private PoiEntity startPoi;
    protected EcCategoryThird selectVariety;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_release_opportunity);
		initView();
		setUpView();
	}

	private void initView() {
		mTopbarView = (TopbarView) this.findViewById(R.id.topbar);

//		mMarketLayout = this.findViewById(R.id.layout_market);
//		mListView = (MeasureListView) this.findViewById(R.id.listview_data_list);
		mMarketNameText = (EditText) this.findViewById(R.id.edittext_market_name);
		mProductNameLayout = this.findViewById(R.id.layout_product_name);
		mProductNameEdit =  (TextView) this.findViewById(R.id.edittext_product_name);
		mUnitNameEdit = (EditText) this.findViewById(R.id.edittext_unit_name);
		mRecivAddressLayout = this.findViewById(R.id.layout_recev_address);
        mRecivAddressText = (TextView) this.findViewById(R.id.textview_recev_address);
        mDetailAddressText = (EditText) this.findViewById(R.id.textview_recev_address_detail);
		mContactPhoneEdit = (EditText) this.findViewById(R.id.edittext_phone);
		mContactNameEdit = (EditText) this.findViewById(R.id.edittext_contact_name);
		mNextButton = (Button) this.findViewById(R.id.button_next);
		
		mPinzhongGv = (MeasureGridView) this.findViewById(R.id.gv_pinzhong);
	}
	

	private void setUpView() {
		mTopbarView.setCenterText("发布商机");
		mTopbarView.setLeftView(true, true);

//		mMarketLayout.setOnClickListener(this);
		mRecivAddressLayout.setOnClickListener(this);
		mNextButton.setOnClickListener(this);
		
		mPinzhongGv.setOnItemClickListener(mVarietyItemListener);
		
//		mListView.setOnItemClickListener(new OnItemClickListener() {
//
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                Market market = (Market) parent.getItemAtPosition(position);
//                deleteMarket(market);
//            }
//        });
		
		mProductNameLayout.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				selectProduct();
			}
		});
	}
	
	private OnItemClickListener mVarietyItemListener = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            selectVariety = (EcCategoryThird) parent.getItemAtPosition(position);
//            if(variety.isSelect()){
//                mSelectVarietyList.remove(variety);
//                variety.setSelect(false);
//            }else{
//                mSelectVarietyList.add(variety);
//                variety.setSelect(true);
//            }
            mVarietyAdapter.setSelectPosition(position);
//            mVarietyAdapter.notifyDataSetChanged();
        }
    };
	
	
	
	private void selectProduct() {
        Intent intent = new Intent(this,ProductTypeActivity.class);
        intent.putExtra(ExtraName.action, true);
        startActivityForResult(intent, SELECT_PRODUCT_TYPE);
    }
	

    protected void deleteMarket(final Market market) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("确定刪除  "+market.getName()+"  ?");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                mMarketList.remove(market);
                mMarketAdapter.setData(mMarketList);
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.create().show();
    }

    @Override
    public void onClick(View v) {
        DeviceHelper.hideIME(mTopbarView);
        switch (v.getId()) {
//        case R.id.layout_market:
//            selectMarketCity();
//            break;
        case R.id.layout_recev_address:
            selectAddressPoi();
            break;
        case R.id.button_next:
            release();
            break;
        }
    }
    
 // 级联菜单选择回调接口
  	class NMCascadingMenuViewOnSelectListener implements
  			CascadingMenuViewOnSelectListener {

  		@Override
  		public void getValue(Area city, String fullname) {
  			mRecivAddressText.setText(fullname);
  			startPoi = PoiEntityUtils.convert(city, fullname);
  		}

  	}
    
    private void selectAddressPoi() {
//    	new CascadingMenuPopWindow().showInstance(this, mRecivAddressText, new NMCascadingMenuViewOnSelectListener());
    	if (cascadingMenuPopWindow == null) {
			//向三级menu添加地区数据
			cascadingMenuPopWindow = new CascadingMenuPopWindow(this, false);
			cascadingMenuPopWindow
					.setMenuViewOnSelectListener(new NMCascadingMenuViewOnSelectListener());
			cascadingMenuPopWindow.showAsDropDown(mRecivAddressText, 5, 5);
		} else if (cascadingMenuPopWindow != null
				&& cascadingMenuPopWindow.isShowing()) {
			cascadingMenuPopWindow.dismiss();
		} else {
			cascadingMenuPopWindow.showAsDropDown(mRecivAddressText, 5, 5);
		}
//        Intent intent1 = new Intent(this, SelectCountrysActivity.class);
//        startActivityForResult(intent1, SELECT_ADDRESS_POI);
    }
    private void release() {
        
        BusinessPublish businessPublish = new BusinessPublish();
        
        String productName = mProductNameEdit.getText().toString().trim();
        String unitName = mUnitNameEdit.getText().toString().trim();
        String phone = mContactPhoneEdit.getText().toString().trim();
        String contactName = mContactNameEdit.getText().toString().trim();
        String address = mDetailAddressText.getText().toString().trim();
        
        String supplymarket = mMarketNameText.getText().toString().trim();
        
//        if(TextUtils.isEmpty(supplymarket)){
//            showToast("我为他供货不能为空");
//            return;
//        }
        
        if(ecCategorySecond == null){
            showToast("请选择产品分类");
            return;
        }
        if(startPoi == null ){
            showToast("请选择单位地址");
            return;
        }
        
        if(TextUtils.isEmpty(address)){
            showToast("请输入详细地址");
            return;
        }
        
        if(TextUtils.isEmpty(contactName)){
            showToast("请输入联系人姓名");
            return;
        }
        if(TextUtils.isEmpty(phone)){
            showToast("请输入联系人电话");
            return;
        }
        if(!StringHelper.isPhoneNumber(phone)){
            showToast("请输入合格的联系人电话");
            return;
        }
        
        String cityid = startPoi.getId();
        String lng = startPoi.getLng()+"";
        String lat = startPoi.getLat()+"";
        
        String bigpid = ecCategorySecond.getBigpid();
        String pid = ecCategorySecond.getCatid();
        
        String catid = "";
        if(selectVariety != null){
            catid = selectVariety.getPid();
        }
        
//        StringBuilder sb = new StringBuilder();
//        for(Market market:mMarketList){
//            sb.append(market.getId());
//        }
        
        businessPublish.setCityid(cityid);
        businessPublish.setLng(lng);
        businessPublish.setLat(lat);
        businessPublish.setBigpid(bigpid);
        businessPublish.setPid(pid);
        businessPublish.setCatid(catid);
        businessPublish.setRealname(contactName);
        businessPublish.setMobile(phone);
        businessPublish.setUnit(unitName);
        businessPublish.setAddress(mRecivAddressText.getText().toString() + address);
        businessPublish.setSupplymarket(supplymarket);
        
        
        
        startLoadingDialog();
        RequestService.getInstance().businessPublish(this, businessPublish, BaseEntity.class, new RequestListener() {
            
            @Override
            public void onSuccess(int requestCode, BaseEntity resultData) {
                dismissLoadingDialog();
                if(resultData.isOk()){
                    showToast("发布成功");
                    finish();
                }else{
                    showToast(resultData.getMsg());
                }
            }
            
            @Override
            public void onFailed(int requestCode, Exception error, String msg) {
                dismissLoadingDialog();
                showToast(R.string.please_check_network);
            }
        });
        
    }

    private void selectMarketCity() {
        Intent intent = new Intent(this,SelectProvinceActivity.class);
        startActivityForResult(intent, SELECT_MARKET_CITY);
    }
    
    private void selectMarket() {
        Intent intent = new Intent(this,SelectMarketActivity.class);
        intent.putExtra(ExtraName.proid, marketProvince.getProid());
        intent.putExtra(ExtraName.citycode, marketCity.getCitycode());
        startActivityForResult(intent, SELECT_MARKET);
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
            case SELECT_PRODUCT_TYPE:
                EcCategorySecond second = (EcCategorySecond) data.getSerializableExtra(ExtraName.ecCategorySecond);
                if(ecCategorySecond != null && !TextUtils.isEmpty(ecCategorySecond.getCatid()) && ecCategorySecond.getCatid().equals(second.getCatid())){
                }else{
                	
                	if(ecCategorySecond != null && second.getCatname().equals("全部") && ecCategorySecond.getCatname().equals("全部") ){
                		return;
                	}
                    ecCategorySecond = second;
                    mProductNameEdit.setText(ecCategorySecond.getCatname());
                    mSelectVarietyList.clear();
                    getVariety(ecCategorySecond);
                }  
                break;
            case SELECT_MARKET_CITY:
                marketProvince = (Province) data.getSerializableExtra(ExtraName.province);
                marketCity = (City) data.getSerializableExtra(ExtraName.city);
                selectMarket();
                break;
//            case SELECT_MARKET:
//                Market selectMarket = (Market) Data.getSerializableExtra(ExtraName.market);
//                boolean isContains = false;
//                for(Market market:mMarketList){
//                    if(market.getId().equals(selectMarket.getId())){
//                        isContains = true;
//                        break;
//                    }
//                }
//                if(!isContains){
//                    mMarketList.add(selectMarket);
//                    setMarketAdapter();
//                }
////                mPifashichangEdit.setText(selectMarket.getName());
//                break;
            case SELECT_ADDRESS_POI:
                startPoi = (PoiEntity) data.getSerializableExtra(ExtraName.poi);
                mRecivAddressText.setText(startPoi.getTitle());
                break;
            }
        }
    }

    private void getVariety(EcCategorySecond item) {
        startLoadingDialog();
        RequestService.getInstance().getEcCategoryVariety(this, item.getBigpid(), item.getCatid(), EcVarietyEntity.class, new RequestListener() {
            
            @Override
            public void onSuccess(int requestCode, BaseEntity resultData) {
                dismissLoadingDialog();
                if(resultData.isOk()){
                    EcVarietyEntity entity = (EcVarietyEntity) resultData;
                    setVarietyAdapter(entity.getData().getList());
                }else{
                    showToast(resultData.getMsg());
                }
            }
            
            @Override
            public void onFailed(int requestCode, Exception error, String msg) {
                dismissLoadingDialog();
                showToast(R.string.please_check_network);
            }
        });
    }
    
    protected void setVarietyAdapter(List<EcCategoryThird> list) {
        if(mVarietyAdapter == null){
            mVarietyAdapter = new VarietyGridviewAdapter<>(this, list, false);
            mVarietyAdapter.setSingleSeletion(true);
            mPinzhongGv.setAdapter(mVarietyAdapter);
        }else{
            mVarietyAdapter.setData(list);
        }
    }
    
//    private void setMarketAdapter() {
//        if(mMarketAdapter == null){
//            mMarketAdapter = new MarketSelectedAdapter<>(this, mMarketList, false);
//            mListView.setAdapter(mMarketAdapter);
//        }else{
//            mMarketAdapter.setData(mMarketList);
//        }
//    }
    @Override
	protected void onDestroy() {
		if (cascadingMenuPopWindow != null) {
			cascadingMenuPopWindow.dismiss();
		}
		super.onDestroy();
	}
}
